package com.cfk.shopmail.product.service.impl;

import com.cfk.shopmail.product.dao.CategoryBrandRelationDao;
import com.cfk.shopmail.product.service.CategoryBrandRelationService;
import com.cfk.shopmail.product.vo.BrandVo;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cfk.common.utils.PageUtils;
import com.cfk.common.utils.Query;

import com.cfk.shopmail.product.dao.BrandDao;
import com.cfk.shopmail.product.entity.BrandEntity;
import com.cfk.shopmail.product.service.BrandService;

import javax.annotation.Resource;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isNullOrEmpty(key)) {
            wrapper.eq("brand_id", key).or().like("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 修改品牌以及与他相关的表信息
     * @param brand
     */
    @Override
    public void updateDetail(BrandEntity brand) {
        this.updateById(brand);
        //如果品牌名不为空
        if (!StringUtils.isNullOrEmpty(brand.getName())) {
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());

            //TODO

        }

    }

    @Override
    public List<BrandVo> getBrandsByIds(List<Long> brandIds) {
        List<BrandEntity> brandEntities = baseMapper.selectList(new QueryWrapper<BrandEntity>().in("brand_id", brandIds));
        List<BrandVo> collect = brandEntities.stream().map(brandEntity -> {
            BrandVo vo = new BrandVo();
            BeanUtils.copyProperties(brandEntity, vo);
            vo.setBrandName(brandEntity.getName());
            return vo;
        }).collect(Collectors.toList());


        return collect;
    }

}